package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.AttendanceSummaryQueryListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.AttendanceSummaryQuery;
import com.isunland.managesystem.entity.AttendanceSummaryQueryOriginal;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * 对象功能: 考勤申请单汇总查询 fragment
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/2/14 16:33
 */
public class AttendanceSummaryQueryListFragment extends BaseListFragment {
  //接收考勤汇总中单据明细传过来的数据
  protected static final String EXTRA_VALUE =
      "com.isunland.managesystem.ui.AttendanceSummaryQueryListFragment.EXTRA_VALUE";

  private final int REQUEST_QUERY = 0;
  private AttendanceSummaryQueryListAdapter mAdapter;
  private int mPage = 1;
  private String regStaffCode;
  private String regStaffName;
  private String dataStatusCode;
  private String dataStatusName;
  private String startDate;
  private String endDate;
  private HashMap<String, String> typeMap = new HashMap<>();//考勤申请单类型
  private CustomerDialog regStaff;//申请人(name,code)
  private CustomerDialog dataStatus;//数据状态
  private CustomerDialog dataTime;//时间
  private TextView mNameTv;
  private TextView mStartDateTv;
  private TextView mEndDateTv;
  private CustomerDialog extraContent;
  private ArrayList<AttendanceSummaryQuery> mList;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setTitle(R.string.attendanceSummaryQuery);
    }
    CurrentUser mUser = CurrentUser.newInstance(getActivity());
    regStaffName = mUser.getRealName();
    regStaffCode = mUser.getJobNumber();
    dataStatusCode = "";
    dataStatusName = getString(R.string.all);
    startDate = MyDateUtil.getBeforeMonthFirstDay(1);
    //noinspection deprecation
    endDate = MyDateUtil.parseDateToString(new Date());
    typeMap = new HashMap<>();
    typeMap.put("holy", "T");
    typeMap.put("outWork", "T");
    typeMap.put("overTime", "T");
    typeMap.put("trip", "T");
    typeMap.put("unpunch", "T");
    typeMap.put("useablePayHoly", "T");
    extraContent = (CustomerDialog) getArguments().getSerializable(EXTRA_VALUE);
    if (extraContent != null) {
      regStaffName = extraContent.getName();
      startDate = extraContent.getId();
      endDate = extraContent.getId();
    }
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    View header = getLayoutInflater(savedInstanceState).inflate(R.layout.header_sign, null, false);
    header.setOnClickListener(new View.OnClickListener() {

      @Override public void onClick(View v) {
        if (extraContent == null) {
          startQuery();
        }
      }
    });
    mNameTv = (TextView) header.findViewById(R.id.tv_name_signHeader);
    mStartDateTv = (TextView) header.findViewById(R.id.tv_startDate_signHeader);
    mEndDateTv = (TextView) header.findViewById(R.id.tv_endDate_signHeader);
    updateHeader();
    mListview.addHeaderView(header);
    mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
    //mListview.setDividerHeight(0);
  }

  private void updateHeader() {
    mStartDateTv.setText(startDate);
    mEndDateTv.setText(endDate);
    mNameTv.setText(
        MyStringUtil.isEmpty(regStaffName) ? getString(R.string.pleaseSelect) : regStaffName);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if (extraContent == null) {
      inflater.inflate(R.menu.menu_query, menu);
    } else {
      super.onCreateOptionsMenu(menu, inflater);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        //                if (NavUtils.getParentActivityName(getActivity()) != null) {
        //                    NavUtils.navigateUpFromSameTask(getActivity());
        //                }
        getActivity().finish();
        return true;
      case R.id.menu_item_query:
        //查询
        startQuery();

        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void startQuery() {
    regStaff = new CustomerDialog(regStaffName, regStaffCode);
    dataStatus = new CustomerDialog(dataStatusName, dataStatusCode);
    dataTime = new CustomerDialog(endDate, startDate);

    Intent query = new Intent(getActivity(), AttendanceSummaryListQueryActicity.class);
    query.putExtra(AttendanceSummaryListQueryFragment.EXTRA_STAFF, regStaff);
    query.putExtra(AttendanceSummaryListQueryFragment.EXTRA_DATASTATUS, dataStatus);
    query.putExtra(AttendanceSummaryListQueryFragment.EXTRA_DATATIME, dataTime);
    query.putExtra(AttendanceSummaryListQueryFragment.EXTRA_TYPE, typeMap);
    startActivityForResult(query, REQUEST_QUERY);
  }

  @Override public String getUrl() {
    return ApiConst.URL_ATTENDANCE_SUMMARY_QUERY;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("arrJobNames", regStaffName);
    params.put("beginregDate", startDate);
    params.put("dataStatus", dataStatusCode);
    params.put("dateFormat", "yyyy-MM-dd HH:mm:ss");
    params.put("endregDate", endDate);
    params.put("holy", typeMap.get(AttendanceSummaryListQueryFragment.VALUE_HOLY));
    params.put("outWork", typeMap.get(AttendanceSummaryListQueryFragment.VALUE_OUT));
    params.put("overTime", typeMap.get(AttendanceSummaryListQueryFragment.VALUE_OVER));
    params.put("trip", typeMap.get(AttendanceSummaryListQueryFragment.VALUE_TRIP));
    params.put("unpunch", typeMap.get(AttendanceSummaryListQueryFragment.VALUE_UNPUNCH));
    params.put("useablePayHoly", typeMap.get(AttendanceSummaryListQueryFragment.VALUE_OFF));
    params.put("page", mPage + "");
    params.put("rows", "20");
    params.put("type", "mobile");
    return params;
  }

  @Override public void resolveResponse(String json) {
    AttendanceSummaryQueryOriginal original =
        new Gson().fromJson(json, AttendanceSummaryQueryOriginal.class);
    ArrayList<AttendanceSummaryQuery> rows = original.getRows();
    if (rows != null && rows.size() == 0) {
      ToastUtil.show(R.string.that_is_all);
    }
    setAdapter(rows);
  }

  public void setAdapter(ArrayList<AttendanceSummaryQuery> rows) {
    if (rows == null) {
      rows = new ArrayList<>();
    }
    //在这里初始化 adapter,否则不显示进度.
    if (mList == null) mList = new ArrayList<>();
    if (mAdapter == null) {
      mAdapter = new AttendanceSummaryQueryListAdapter(mActivity, mList);
      setListAdapter(mAdapter);
    }
    if (mPage == 1) {
      mList.clear();
    }
    mList.addAll(rows);
    mAdapter.notifyDataSetChanged();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {

    AttendanceSummaryQuery mcontent = mAdapter.getItem(position - 2);
    Intent i = new Intent(getActivity(), CheckDetailActivity.class);
    i.putExtra(CheckDetailFragment.EXTRA_REQUISITION_ID, mcontent.getID());
    i.putExtra(CheckDetailFragment.EXTRA_TYPE, mcontent.getTYPE_CODE());
    i.putExtra(CheckDetailFragment.EXTRA_INTERRUPT, "");
    i.putExtra(CheckDetailFragment.EXTRA_FILE, "");
    i.putExtra(CheckDetailFragment.EXTRA_DATASTATUS, DataStatus.CHECK_PASS);
    i.putExtra(CheckDetailFragment.EXTRA_IFALLOW, mcontent.getIFALLOWSUPPLEMENT());
    startActivity(i);
    super.onListItemClick(l, v, position, id);
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {
    PullToRefreshBase.Mode mode = refreshView.getCurrentMode();
    if (mode.equals(PullToRefreshBase.Mode.PULL_FROM_START)) {
      mPage = 1;
    }
    if (mode.equals(PullToRefreshBase.Mode.PULL_FROM_END)) {
      mPage++;
    }
    volleyPost();
  }

  @SuppressWarnings("unchecked") @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_QUERY) {
      regStaff = (CustomerDialog) data.getSerializableExtra(
          AttendanceSummaryListQueryFragment.EXTRA_STAFF);
      dataStatus = (CustomerDialog) data.getSerializableExtra(
          AttendanceSummaryListQueryFragment.EXTRA_DATASTATUS);
      dataTime = (CustomerDialog) data.getSerializableExtra(
          AttendanceSummaryListQueryFragment.EXTRA_DATATIME);
      typeMap = (HashMap<String, String>) data.getSerializableExtra(
          AttendanceSummaryListQueryFragment.EXTRA_TYPE);

      regStaffCode = regStaff.getId();
      regStaffName = regStaff.getName();
      dataStatusCode = dataStatus.getId();
      dataStatusName = dataStatus.getName();
      startDate = dataTime.getId();
      endDate = dataTime.getName();
      updateHeader();
      mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
      mPage = 1;
      volleyPost();
      mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
    }
  }

  public static AttendanceSummaryQueryListFragment newInstance(CustomerDialog extraContent) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_VALUE, extraContent);
    AttendanceSummaryQueryListFragment fragment = new AttendanceSummaryQueryListFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
